#!/bin/bash

EEPROM_PATH="/sys/bus/i2c/drivers/at24/2-0050/eeprom"
FRAM_PATH="/sys/bus/i2c/drivers/at24/3-0050/eeprom"
DEVICE=$EEPROM_PATH
OFFSET=1
SN_DATA=""
SN_MAX_LENGTH=25
DUMP_FORMAT="$SN_MAX_LENGTH/1 \"%c\" \"\\n\"" 

show_help()
{
        echo -e \
"Usage:\n\
 $0 [options]\n\n\
Read SN to EEPROM or FRAM\n\n\
Options:\n\
 -i <E|F>		Read to E:EEPROM, F:FRAM (default:EEPROM)\n\
 -s <offset>		ofset (default:$OFFSET)\n\
 -l <length>		SN length ((default:$SN_MAX_LENGTH))\n"
}

# A POSIX variable                                                             
OPTIND=1         # Reset in case getopts has been used previously in the shell.
                                                                               
while getopts "i:s:l:h?" opt; do                                                 
        case "$opt" in                                                         
        s)                                                                     
                OFFSET=$OPTARG                                             
                ;;                                 
	i)
		if [[ "$OPTARG" = "F" ]]; then
			DEVICE=$FRAM_PATH
		fi
		;;
        l)                                                                     
                SN_MAX_LENGTH=$OPTARG                                                 
                ;;                                  
        h|\?)                                      
                show_help                          
                exit 0                                                         
                ;;                                                             
        esac                                                                   
done

# Check inpurt argument
re='^[0-9]+$'
if ! [[ "$OFFSET" =~ $re ]]; then
	echo "Error: OFFSET must be an number"
	exit 1
fi

if ! [[ "$SN_MAX_LENGTH" =~ $re ]]; then                                              
        echo "Error: LENGTH must be an number"                                 
        exit 1                                                                 
fi                                                                             

# Read data from EEPROM                                                
SN_DATA=$(hexdump -s $OFFSET -n $SN_MAX_LENGTH -e "$DUMP_FORMAT" $DEVICE | tr '\0' '\n' | cut -d $'\n' -f1)                            
if [[ -z "${SN_DATA//[a-zA-Z0-9]}" ]]; then                                     
        echo -e "$SN_DATA"                                                      
fi  
